package com.qing.qingapiclientsdk.Client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import com.qing.qingapiclientsdk.Model.User;
import com.qing.qingapiclientsdk.utils.SignUtils;


import java.nio.charset.StandardCharsets;

import java.util.HashMap;
import java.util.Map;

import static com.qing.qingapiclientsdk.utils.SignUtils.getSign;

/**
 * 调用第三方接口的客户端
 *
 * @author qingfengzy
 */
public class QingApiClient {

    private static final String GATEWAY_HOST = "http://localhost:8123";
    String accessKey;
    String secretKey;

    public QingApiClient(String accessKey,String secretKey){
        this.accessKey=accessKey;
        this.secretKey=secretKey;
    }


    SignUtils signUtils = new SignUtils();
    public String getNameByGet(String name){
//        可以单独传入http参数，这样参数会自动做url编码，拼接到URL中
        HashMap<String,Object> paramMap = new HashMap<>();
        paramMap.put("name",name);
        String result = HttpUtil.get(GATEWAY_HOST+"/api/name/",paramMap);
        System.out.println(result);
        return result;
    }

    public String getNameByPost(String name){
        //        可以单独传入http参数，这样参数会自动做url编码，拼接到URL中
        HashMap<String,Object> paramMap = new HashMap<>();
        paramMap.put("name",name);
        String result = HttpUtil.post(GATEWAY_HOST+"/api/name/", paramMap);
        System.out.println(result);
        return result;
    }

//    创建一个装ak和sk的队列
    private Map<String,String> getHeaderMap(String body){
        Map<String,String> hashMap = new HashMap<>();

        hashMap.put("accessKey",accessKey);
//        hashMap.put("secretKey",secretKey);
//        一定不能直接传输发送
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body",body);
        hashMap.put("timestamp",String.valueOf(System.currentTimeMillis()/ 1000));
        hashMap.put("sign",getSign(body,secretKey));
//        这个getsign是加密算法
       return hashMap;
    }




    public String getUsernameByPost(User user) {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST + "/api/name/user")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println(result);
        return result;
    }
}



